import {Injectable} from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class Token {

  private tokenKey = 'token';
  private authKey = 'auth';

  get accessToken(): string {
    const token = this.getToken();
    return token ? token['_accessToken'] : null;
  }

  get refreshToken(): string {
    const token = this.getToken();
    return token ? token['_refreshToken'] : null;
  }

  get tokenType(): string {
    const token = this.getToken();
    return token ? token['_tokenType'] : null;
  }

  get expire(): number {
    const token = this.getToken();
    return token ? token['_expire'] : null;
  }

  getToken(): any {
    const token = localStorage.getItem(this.tokenKey);
    if (!token) {
      return null;
    }
    return JSON.parse(token);
  }

  setToken(res: any) {
    const token = {
      _accessToken: res['access_token'],
      _refreshToken: res['refresh_token'],
      _tokenType: res['token_type'],
      _expire: res['expires_in'] * 1000 + new Date().getTime()
    };
    localStorage.setItem(this.tokenKey, JSON.stringify(token));
  }

  getAuth() {
    return JSON.parse(localStorage.getItem(this.authKey));
  }

  setAuth(auth: any) {
    localStorage.setItem(this.authKey, JSON.stringify(auth));
  }

  logout() {
    localStorage.removeItem(this.tokenKey);
    localStorage.removeItem(this.authKey);
  }
}
